package com.kehutong.auth.service;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;

import com.kehutong.common.IpUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.auth.entity.SmsCode;
import com.kehutong.common.isp.TencentSms;
import com.kehutong.common.util.Token;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;

@WebService("/auth/sms/service")
public class SmsCodeService {
    public static final String CODE = "Ok";
    public static final String COUNTNUMBER = "LimitExceeded.PhoneNumberDailyLimit";

    @Inject
    private TencentSms tencentSms;
    @Inject
    private JdbcSession jdbcSession;

    public SmsCode find(String sessionId, String code) {
        if (Objects.isEmpty(sessionId) || Objects.isEmpty(code)) {
            return null;
        }

        return jdbcSession.findOne(SmsCode.class)
                .eq("sessionId", sessionId)
                .eq("code", code)
                .exe();
    }

    @ReqMapping("/checkSmsCode")
    public Object checkSmsCode(String sessionId, String code) {
        SmsCode smsCode = find(sessionId, code);
        if (Objects.isNull(smsCode)) {
            return Result.error(0, "验证码错误");
        }

        long s = (TimeUtil.timeMillis() - smsCode.getCreateTime().getTime()) / (1000 * 60);
        if (s > 3) {
            return Result.error(0, "验证码已超时");
        }
        return Result.success();
    }

    public Object send(Token token, String mobile) throws Exception {

        SmsCode smsCode = sendSms(token, mobile);
        if (smsCode.getState().equals(CODE)) {
            return Result.success("已发送，请注意查收短信息");
        }

        if (smsCode.getState().equals(COUNTNUMBER)) {
            return Result.error(0, "已超过今天的短信发送上限，明天再来吧");
        }

        return Result.error(0, "发送失败！");
    }

    private SmsCode sendSms(Token token, String mobile) throws Exception {

        List<String> mobiles = Arrays.asList("86" + mobile);

        String randomCode = new StringBuilder().append(randomCode()).toString();

        List<String> randomCodes = Arrays.asList(randomCode, "3");
        JSONObject result = tencentSms.sendSms(mobiles, randomCodes);

        JSONObject responseJson = result.getJSONObject("Response");

        JSONArray sendStatusSets = responseJson.getJSONArray("SendStatusSet");

        JSONObject jsonObject = sendStatusSets.getJSONObject(0);

        //短信发送结果 CODE
        String sendState = jsonObject.getString("Code");

        //短信发送结果 Message
        String message = jsonObject.getString("Message");

        //短信发送内容 SessionContext
        String context = jsonObject.getString("SessionContext");

        SmsCode smsCode = Pool.newInstance(SmsCode.class);
        smsCode.setCode(randomCode);
        smsCode.setContext(MessageFormat.format(context, randomCodes.toArray()));
        smsCode.setSessionId(token.getSessionId());
        smsCode.setMobile(mobile);
        smsCode.setMessage(message);
        smsCode.setState(sendState);
        jdbcSession.insert(smsCode);

        return smsCode;
    }

    private static int randomCode() {
        return ThreadLocalRandom.current().nextInt(100000, 1000000);
    }
}
